import _ from 'lodash'
import inputCommon from '../../../../mixin/inputCommon'
import { invokeInterface, getValidateRule } from '../../../../service'
import * as api from '../../../../service'

export default {
  name: 'inputRender',
  props: ['config', 'editor', 'scope', 'cancelLinkAndDefaultValue', 'readonlyMain'],
  mixins: [inputCommon],
  inject: ['rootForm'],
  data() {
    return {
      scopeErrorMessage: '',
      validateRules: [],
      flag: false // 还未被校验
    }
  },
  methods: {
    // input(value) {
    //   if (!this.scope) {
    //     this.$refs.formItem.$emit('el.form.change', [value])
    //   } else {
    //     this.validate()
    //   }
    //   return this.config.inputCb && this.getParsedFn('inputCb')(value)
    // },
    // blur() {
    //   if (!this.scope) {
    //     this.$refs.formItem.$emit('el.form.blur', [this.rootForm.properties[this.config.propertyName]])
    //   } else {
    //     this.validate()
    //   }
    //   return this.config.blurCb && this.getParsedFn('blurCb')()
    //   // return this.config.blurCb && !!(new Function('__properties', '__row', 'with(__properties) {return (' + this.config.blurCb + ')() }'))(this.rootForm.properties, this.scope)
    // },
    focus(event) {
      return this.config.focusCb && this.getParsedFn('focusCb')(event)
    },
    keydown(event) {
      return this.config.keydownCb && this.getParsedFn('keydownCb')(event)
    },
    keyup(event) {
      return this.config.keyupCb && this.getParsedFn('keyupCb')(event)
    },
    // 针对scope的验证
    validate() {
      if (this.scope) {
        this.flag = true
        let value = this.scope[this.config.propertyName]
        if (this.required && !value) {
          this.scopeErrorMessage = '必填项'
          return false
        } else if (this.validateRules.length > 0) {
          let res = true
          this.scopeErrorMessage = ''
          if (value) {
            this.validateRules.forEach((item) => {
              if (item.type === 'regex') {
                if (!(new RegExp(item.value)).test(value)) {
                  this.scopeErrorMessage = '输入有误'
                  res = false
                }
              } else {
                if (!new Function('value', 'return (' + item.value + ')(value)')(value)) {
                  this.scopeErrorMessage = '输入有误'
                  res = false
                }
              }
            })
            if (this.config.maxlength && !(new RegExp(`^(.|\n|\r){0,${this.config.maxlength}}$`)).test(value)) {
              this.scopeErrorMessage = '最多输入' + this.config.maxlength + '个字符'
              res = false
            }
          }
          return res
        } else if (this.config.maxlength) {
          let res = true
          this.scopeErrorMessage = ''
          if (!(new RegExp(`^(.|\n|\r){0,${this.config.maxlength}}$`)).test(value)) {
            this.scopeErrorMessage = '最多输入' + this.config.maxlength + '个字符'
            res = false
          }
          return res
        }
        this.scopeErrorMessage = ''
        return true
      }
    }
  },
  created() {
    if (this.config.patterns && !this.readonly) {
      getValidateRule(this.config.patterns).then(res => {
        if (res && res.length === 1) {
          this.rules.push({
            validator: (rule, value, callback) => {

              if ((new RegExp(res[0].dataRuleContent)).test(value) || (!value && !this.getParsedEx('required')())) {
                callback()
              }else{
                callback(new Error('输入有误'))
              }
            },
            trigger: 'blur'
          })
        }

      })
    }
    // this.config.maxlength || (this.config.maxlength = 500)
    if (this.config.maxlength && !this.readonly) {
      this.rules.push({
        validator: (rule, value, callback) => {
          if ((new RegExp(`^(.|\n|\r){0,${this.config.maxlength}}$`)).test(value)) {
            callback()
          } else {
            callback(new Error(`最多输入${this.config.maxlength}个字符`))
          }
        },
        trigger: 'blur'
      })
    }
    // 异步关联查询
    if (this.config.inputWay === 'asyncLink') {
      // 数据接口
      if (this.config.connectType === 'interface') {
        let params = {}
        if (this.config.linkSearchEx && this.config.linkSearchQueryKey) {
          let linkSearchExFn = this.getParsedEx('linkSearchEx')
          let v = linkSearchExFn()
          if (v !== 0) {
            v = v || ''
          }
          params = { [this.config.linkSearchQueryKey]: v }
          let debounce = _.debounce(() => {
            let v = linkSearchExFn()
            if (v !== 0) {
              v = v || ''
            }
            let params = {
              [this.config.linkSearchQueryKey]: v
            }
            if (this.config.dataInterfaceId) {
              invokeInterface(this.config.dataInterfaceId, params).then((data) => {
                if (typeof data === 'object') {
                  data = JSON.stringify(data)
                }
                if (!this.cancelLinkAndDefaultValue) {
                  if (this.scope) {
                    this.scope[this.config.propertyName] = data
                  } else {
                    this.rootForm.properties[this.config.propertyName] = data
                  }
                }
              })
            }
          }, 300)
          this.rootForm.$watch(() => {
            return linkSearchExFn()
          }, (newValue, oldValue) => {
            debounce()
          })
        }
        // 初始化数据
        if (this.config.dataInterfaceId) {
          invokeInterface(this.config.dataInterfaceId, params).then((data) => {
            if (typeof data === 'object') {
              data = JSON.stringify(data)
            }
            if (!this.cancelLinkAndDefaultValue) {
              if (this.scope) {
                this.scope[this.config.propertyName] = data
              } else {
                this.rootForm.properties[this.config.propertyName] = data
              }
            }
          })
        }
      } else if (this.config.connectType === 'dictionary') {
        // 数据字典
        if (this.config.dataDictionaryId) {
          api.getDictionaryData(this.config.dataDictionaryId).then(data => {
            if (typeof data === 'object') {
              data = JSON.stringify(data)
            }
            if (!this.cancelLinkAndDefaultValue) {
              if (this.scope) {
                this.scope[this.config.propertyName] = data
              } else {
                this.rootForm.properties[this.config.propertyName] = data
              }
            }
          })
        }
      }
    } else if (this.config.inputWay === 'syncLink') {
      let linkExFn = this.getParsedEx('linkEx')

      this.rootForm.$watch(() => {
        return linkExFn()
      }, (newValue, oldValue) => {
        if (!this.cancelLinkAndDefaultValue) {
          if (this.scope) {
            this.scope[this.config.propertyName] = linkExFn()
          } else {
            this.rootForm.properties[this.config.propertyName] = linkExFn()
          }
        }
      })
      if (!this.cancelLinkAndDefaultValue) {
        if (this.scope) {
          this.scope[this.config.propertyName] = linkExFn()
        } else {
          this.rootForm.properties[this.config.propertyName] = linkExFn()
        }
      }
    }
  }
}
